import axios, { AxiosInstance, AxiosResponse } from "axios";
import {
  ApiResponse,
  Token,
  CreateTokenDto,
  UpdateTokenDto,
  TokensQuery,
  SearchQuery,
  HealthStatus,
  Transaction,
  User
} from "../types/api";
import type { 
  XLayerToken, 
  XLayerStats, 
  CreateXLayerTokenParams,
  XLayerPriceData
} from "../types/xlayer";
import type {
  BSCToken,
  BSCStats,
  CreateBSCTokenParams,
  BSCPriceData,
  BSCContribution
} from "../types/bsc";

class ApiClient {
  private client: AxiosInstance;
  private baseURL: string;

  constructor() {
    // 生产环境硬编码处理
    let apiUrl: string;
    if (typeof window !== 'undefined' && window.location.hostname === 'c4pad.fun') {
      apiUrl = 'https://c4pad.fun/api';
    } else {
      apiUrl = process.env.NEXT_PUBLIC_API_URL || "http://localhost:7172/api";
    }
    
    // 确保 baseURL 是绝对路径
    this.baseURL = apiUrl.startsWith('http') ? apiUrl : `https://${apiUrl}`;

    this.client = axios.create({
      baseURL: this.baseURL,
      timeout: 60000, // 增加到60秒以处理代币创建等长时间操作
      headers: {
        "Content-Type": "application/json",
      },
    });

    // Request interceptor
    this.client.interceptors.request.use(
      (config) => {
        // Add auth token if available
        const token = this.getAuthToken();
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );

    // Response interceptor
    this.client.interceptors.response.use(
      (response: AxiosResponse) => {
        return response;
      },
      (error) => {
        console.error("API Error:", error.response?.data || error.message);
        return Promise.reject(error);
      }
    );
  }

  private getAuthToken(): string | null {
    // Implement token retrieval logic
    if (typeof window !== "undefined") {
      return localStorage.getItem("auth_token");
    }
    return null;
  }

  // Health Check Endpoints
  async getHealth(): Promise<HealthStatus> {
    const response = await this.client.get<HealthStatus>("health");
    return response.data;
  }

  async getDetailedHealth(): Promise<HealthStatus> {
    const response = await this.client.get<HealthStatus>(
      "health/detailed"
    );
    return response.data;
  }

  async getReadiness(): Promise<HealthStatus> {
    const response = await this.client.get<HealthStatus>("health/ready");
    return response.data;
  }

  async getLiveness(): Promise<HealthStatus> {
    const response = await this.client.get<HealthStatus>("health/live");
    return response.data;
  }

  // Bonding Curve endpoints
  async buyToken(
    tokenMint: string,
    solAmount: number,
    buyerPublicKey: string
  ): Promise<
    ApiResponse<{
      transaction: string;
      signature?: string;
      tokenAmount?: number;
      price?: number;
      newTotalSupply?: number;
      isGraduated?: boolean;
    }>
  > {
    const response = await this.client.post<
      ApiResponse<{
        transaction: string;
        signature?: string;
        tokenAmount?: number;
        price?: number;
        newTotalSupply?: number;
        isGraduated?: boolean;
      }>
    >("bonding-curve/buy", {
      tokenMint,
      solAmount,
      buyerPublicKey,
    });
    return response.data;
  }

  async sellToken(
    tokenMint: string,
    tokenAmount: number,
    sellerPublicKey: string
  ): Promise<
    ApiResponse<{
      transaction: string;
      signature?: string;
      solAmount?: number;
      price?: number;
      newTotalSupply?: number;
    }>
  > {
    const response = await this.client.post<
      ApiResponse<{
        transaction: string;
        signature?: string;
        solAmount?: number;
        price?: number;
        newTotalSupply?: number;
      }>
    >("bonding-curve/sell", {
      tokenMint,
      tokenAmount,
      sellerPublicKey,
    });
    return response.data;
  }

  // 获取代币价格信息
  async getTokenPrice(
    tokenMint: string
  ): Promise<ApiResponse<{ price: number; marketCap: number }>> {
    const response = await this.client.get<
      ApiResponse<{ price: number; marketCap: number }>
    >(`bonding-curve/price/${tokenMint}`);
    return response.data;
  }

  // 获取代币联合曲线信息
  async getTokenInfo(tokenMint: string): Promise<
    ApiResponse<{
      totalSupply: number;
      circulatingSupply: number;
      solReserves: number;
      tokenReserves: number;
      isGraduated: boolean;
      marketCap: number;
      price: number;
    }>
  > {
    const response = await this.client.get<
      ApiResponse<{
        totalSupply: number;
        circulatingSupply: number;
        solReserves: number;
        tokenReserves: number;
        isGraduated: boolean;
        marketCap: number;
        price: number;
      }>
    >(`bonding-curve/info/${tokenMint}`);
    return response.data;
  }

  // 创建联合曲线代币
  async createBondingCurveToken(data: {
    name: string;
    symbol: string;
    uri: string;
    creatorPrivateKey: string;
  }): Promise<ApiResponse<{ tokenMint: string; transaction: string }>> {
    const response = await this.client.post<
      ApiResponse<{ tokenMint: string; transaction: string }>
    >("bonding-curve/create-token", data, {
      timeout: 90000, // 90秒超时
    });
    return response.data;
  }

  // Token Management Endpoints
  async getTokens(params?: TokensQuery): Promise<ApiResponse<Token[]>> {
    const response = await this.client.get<ApiResponse<Token[]>>(
      "tokens",
      {
        params,
      }
    );
    return response.data;
  }

  async getTrendingTokens(limit?: number): Promise<ApiResponse<Token[]>> {
    const response = await this.client.get<ApiResponse<Token[]>>(
      "tokens/trending",
      {
        params: { limit },
      }
    );
    return response.data;
  }

  async searchTokens(params: SearchQuery): Promise<ApiResponse<Token[]>> {
    const response = await this.client.get<ApiResponse<Token[]>>(
      "tokens/search",
      {
        params,
      }
    );
    return response.data;
  }

  async getToken(mint: string): Promise<ApiResponse<Token>> {
    const response = await this.client.get<ApiResponse<Token>>(
      `tokens/${mint}`
    );
    return response.data;
  }

  async createToken(data: CreateTokenDto): Promise<ApiResponse<Token>> {
    // 为代币创建设置更长的超时时间（90秒）
    const response = await this.client.post<ApiResponse<Token>>(
      "tokens",
      data,
      {
        timeout: 90000, // 90秒超时，因为代币创建涉及多个区块链交易
      }
    );
    return response.data;
  }

  async updateToken(
    mint: string,
    data: UpdateTokenDto
  ): Promise<ApiResponse<Token>> {
    const response = await this.client.put<ApiResponse<Token>>(
      `tokens/${mint}`,
      data
    );
    return response.data;
  }

  async syncTokenMetadata(mint: string): Promise<ApiResponse<Token>> {
    const response = await this.client.post<ApiResponse<Token>>(
      `tokens/${mint}/sync`
    );
    return response.data;
  }

  async updateTokenPrice(
    mint: string
  ): Promise<ApiResponse<{ mint: string; price: number; marketCap: number }>> {
    const response = await this.client.post<
      ApiResponse<{ mint: string; price: number; marketCap: number }>
    >(`tokens/${mint}/price`);
    return response.data;
  }

  async deleteToken(mint: string): Promise<ApiResponse<void>> {
    const response = await this.client.delete<ApiResponse<void>>(
      `tokens/${mint}`
    );
    return response.data;
  }

  // Upload image file
  async uploadImage(file: File): Promise<ApiResponse<{ url: string }>> {
    const formData = new FormData();
    formData.append("image", file);

    const response = await this.client.post<ApiResponse<{ url: string }>>(
      "upload/image",
      formData,
      {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      }
    );
    return response.data;
  }

  // Utility methods
  getWebSocketUrl(): string {
    // 优先使用环境变量中的 WebSocket URL
    const envWsUrl = process.env.NEXT_PUBLIC_WS_URL;
    if (envWsUrl) {
      return envWsUrl;
    }

    // 如果没有设置环境变量，则基于 API URL 生成 WebSocket URL
    let baseUrl = this.baseURL;
    if (baseUrl.endsWith("/api")) {
      baseUrl = baseUrl.slice(0, -4);
    }

    const wsProtocol = baseUrl.startsWith("https") ? "wss" : "ws";
    const baseUrlWithoutProtocol = baseUrl.replace(/^https?:\/\//, "");
    return `${wsProtocol}://${baseUrlWithoutProtocol}/realtime`;
  }

  getWebSocketBaseUrl(): string {
    // 生产环境硬编码处理
    if (typeof window !== 'undefined' && window.location.hostname === 'c4pad.fun') {
      return 'wss://c4pad.fun';
    }
    
    // 优先使用环境变量中的 WebSocket URL
    const envWsUrl = process.env.NEXT_PUBLIC_WS_URL;
    if (envWsUrl) {
      // 如果环境变量包含/realtime，移除它，因为Socket.IO会使用命名空间
      return envWsUrl.replace('/realtime', '');
    }

    // 如果没有设置环境变量，则基于 API URL 生成 WebSocket 基础URL
    let baseUrl = this.baseURL;
    if (baseUrl.endsWith("/api")) {
      baseUrl = baseUrl.slice(0, -4);
    }

    const wsProtocol = baseUrl.startsWith("https") ? "wss" : "ws";
    const baseUrlWithoutProtocol = baseUrl.replace(/^https?:\/\//, "");
    return `${wsProtocol}://${baseUrlWithoutProtocol}`;
  }

  getApiDocsUrl(): string {
    return `${this.baseURL}/docs`;
  }

  // 记录交易
  async recordTransaction(data: {
    signature: string;
    type: 'BUY' | 'SELL';
    tokenMint: string;
    userPublicKey: string;
    amount: number;
    metadata?: Record<string, unknown>;
  }): Promise<ApiResponse<{ id: string; signature: string }>> {
    const response = await this.client.post('/bonding-curve/record-transaction', data);
    return response.data;
  }

  // X Layer API Methods
  
  // Get X Layer statistics
  async getXLayerStats(): Promise<XLayerStats> {
    const response = await this.client.get<XLayerStats>('/xlayer/stats');
    return response.data;
  }

  // Get X Layer tokens
  async getXLayerTokens(params?: {
    page?: number;
    limit?: number;
    search?: string;
    filter?: 'all' | 'active' | 'launched' | 'cancelled';
    sort?: 'newest' | 'oldest' | 'price_high' | 'price_low' | 'market_cap' | 'volume';
  }): Promise<{ tokens: XLayerToken[]; pagination: { page: number; limit: number; total: number; pages: number } }> {
    const response = await this.client.get('/xlayer/tokens', { params });
    return response.data;
  }

  // Get specific X Layer token
  async getXLayerToken(id: string): Promise<XLayerToken | null> {
    try {
      const response = await this.client.get<XLayerToken>(`/xlayer/tokens/${id}`);
      return response.data;
    } catch (error) {
      console.error('Error fetching X Layer token:', error);
      return null;
    }
  }

  // Get X Layer token chart data
  async getXLayerTokenChart(id: string, timeframe: '1h' | '24h' | '7d' | '30d' = '24h'): Promise<{
    prices: XLayerPriceData[];
    timeframe: string;
  }> {
    const response = await this.client.get(`/xlayer/tokens/${id}/chart`, {
      params: { timeframe }
    });
    return response.data;
  }

  // Create X Layer token
  async createXLayerToken(data: CreateXLayerTokenParams & { imageUrl?: string }): Promise<XLayerToken> {
    const response = await this.client.post<XLayerToken>('/xlayer/tokens', data, {
      timeout: 90000 // 90 seconds for contract interaction
    });
    return response.data;
  }

  // Contribute to X Layer token
  async contributeToXLayerToken(tokenId: string, data: {
    contributor: string;
    amount: string;
    txHash?: string;
  }): Promise<{ success: boolean; tokensReceived?: string; newRaisedAmount?: string }> {
    const response = await this.client.post(`/xlayer/tokens/${tokenId}/contribute`, data, {
      timeout: 60000 // 60 seconds for blockchain transaction
    });
    return response.data;
  }

  // Get user's X Layer tokens
  async getUserXLayerTokens(address: string): Promise<XLayerToken[]> {
    const response = await this.client.get<XLayerToken[]>(`/xlayer/users/${address}/tokens`);
    return response.data;
  }

  // Get user's X Layer contributions
  async getUserXLayerContributions(address: string): Promise<BSCContribution[]> {
    const response = await this.client.get(`/xlayer/users/${address}/contributions`);
    return response.data;
  }

  // Upload X Layer token image
  async uploadXLayerImage(file: File): Promise<{ url: string }> {
    const formData = new FormData();
    formData.append('image', file);
    
    const response = await this.client.post('/xlayer/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      timeout: 30000 // 30 seconds for file upload
    });
    return response.data;
  }

  // Sync X Layer token from contract
  async syncXLayerToken(tokenId: string): Promise<XLayerToken> {
    const response = await this.client.put<XLayerToken>(`/xlayer/tokens/${tokenId}/sync`);
    return response.data;
  }

  // Get X Layer token holders
  async getXLayerTokenHolders(tokenId: string): Promise<User[]> {
    const response = await this.client.get(`/xlayer/tokens/${tokenId}/holders`);
    return response.data;
  }

  // Get X Layer token transactions
  async getXLayerTokenTransactions(tokenId: string, limit = 50): Promise<Transaction[]> {
    const response = await this.client.get(`/xlayer/tokens/${tokenId}/transactions`, {
      params: { limit }
    });
    return response.data;
  }

  // Buy X Layer tokens
  async buyXLayerTokens(launchId: number, data: {
    buyerAddress: string;
    buyerPrivateKey: string;
    ethAmount: number;
  }): Promise<{
    txHash: string;
    tokensReceived: string;
    newPrice: string;
  }> {
    const response = await this.client.post(`/xlayer/tokens/${launchId}/buy`, data, {
      timeout: 120000 // 2 minutes for blockchain transaction
    });
    return response.data;
  }

  // Prepare X Layer buy transaction (for wallet signing)
  async prepareXLayerBuy(launchId: number, data: {
    buyerAddress: string;
    ethAmount: number;
  }): Promise<{
    success: boolean;
    transaction: {
      to: string;
      value: string;
      data: string;
      gasLimit: string;
    };
    estimate: {
      ethAmount: number;
      tokensToReceive: string;
      launchId: number;
    };
  }> {
    const response = await this.client.post(`/xlayer/tokens/${launchId}/prepare-buy`, data);
    return response.data;
  }

  // Confirm X Layer buy transaction
  async confirmXLayerBuy(launchId: number, data: {
    txHash: string;
    buyerAddress: string;
    ethAmount: number;
  }): Promise<{
    success: boolean;
    message: string;
    contribution?: {
      id: number;
      launchId: number;
      contributor: string;
      amount: string;
      tokensReceived: string;
      tradeType: string;
      txHash: string;
      timestamp: number;
    };
    tokensReceived?: string;
    newPrice?: string;
  }> {
    const response = await this.client.post(`/xlayer/tokens/${launchId}/confirm-buy`, data);
    return response.data;
  }

  // Sell X Layer tokens
  async sellXLayerTokens(launchId: number, data: {
    sellerAddress: string;
    sellerPrivateKey: string;
    tokenAmount: number;
  }): Promise<{
    txHash: string;
    ethReceived: string;
    newPrice: string;
  }> {
    const response = await this.client.post(`/xlayer/tokens/${launchId}/sell`, data, {
      timeout: 120000 // 2 minutes for blockchain transaction
    });
    return response.data;
  }

  // Prepare X Layer sell transaction (for wallet signing)
  async prepareXLayerSell(launchId: number, data: {
    sellerAddress: string;
    tokenAmount: number;
  }): Promise<{
    success: boolean;
    transaction: {
      to: string;
      value: string;
      data: string;
      gasLimit: string;
    };
    estimate: {
      tokenAmount: number;
      ethToReceive: string;
      launchId: number;
    };
  }> {
    const response = await this.client.post(`/xlayer/tokens/${launchId}/prepare-sell`, data);
    return response.data;
  }

  // Prepare X Layer approve transaction (for token allowance)
  async prepareXLayerApprove(launchId: number, data: {
    userAddress: string;
    tokenAmount: number;
  }): Promise<{
    success: boolean;
    transaction: {
      to: string;
      value: string;
      data: string;
      gasLimit: string;
    };
    estimate: {
      tokenAmount: number;
      spender: string;
      launchId: number;
      tokenAddress: string;
    };
  }> {
    const response = await this.client.post(`/xlayer/tokens/${launchId}/prepare-approve`, data);
    return response.data;
  }

  // Cancel X Layer token launch (creator only)
  async cancelXLayerLaunch(launchId: number, data: {
    creatorAddress: string;
    creatorPrivateKey: string;
  }): Promise<{
    success: boolean;
    txHash: string;
    message: string;
  }> {
    const response = await this.client.post(`/xlayer/tokens/${launchId}/cancel`, data, {
      timeout: 120000 // 2 minutes for blockchain transaction
    });
    return response.data;
  }

  // Prepare X Layer cancel transaction (for wallet signing)
  async prepareXLayerCancel(launchId: number, data: {
    creatorAddress: string;
  }): Promise<{
    success: boolean;
    transaction: {
      to: string;
      value: string;
      data: string;
      gasLimit: string;
    };
    estimate: {
      launchId: number;
      creator: string;
    };
  }> {
    const response = await this.client.post(`/xlayer/tokens/${launchId}/prepare-cancel`, data);
    return response.data;
  }

  // Claim refund from cancelled X Layer token
  async claimXLayerRefund(launchId: number, data: {
    contributorAddress: string;
    contributorPrivateKey: string;
  }): Promise<{
    success: boolean;
    txHash: string;
    refundAmount: string;
    message: string;
  }> {
    const response = await this.client.post(`/xlayer/tokens/${launchId}/refund`, data, {
      timeout: 120000 // 2 minutes for blockchain transaction
    });
    return response.data;
  }

  // Prepare X Layer refund transaction (for wallet signing)
  async prepareXLayerRefund(launchId: number, data: {
    contributorAddress: string;
  }): Promise<{
    success: boolean;
    error?: string;
    needsApproval?: boolean;
    approvalData?: {
      tokenAddress: string;
      spenderAddress: string;
      requiredAmount: string;
      currentAllowance: string;
    };
    transaction?: {
      to: string;
      value: string;
      data: string;
      gasLimit: string;
      gasPrice?: string; // 添加可选的gasPrice字段
    };
    estimate?: {
      launchId: number;
      contributor: string;
      refundAmount: string;
      estimatedGasFee?: string; // 添加可选的估算gas费用字段
    };
  }> {
    const response = await this.client.post(`/xlayer/tokens/${launchId}/prepare-refund`, data);
    return response.data;
  }

  // Confirm X Layer refund transaction (after successful wallet transaction)
  async confirmXLayerRefund(launchId: number, data: {
    contributorAddress: string;
    txHash: string;
  }): Promise<{
    success: boolean;
    message: string;
    contribution?: {
      id: string;
      launchId: number;
      contributor: string;
      amount: string;
      tokensReceived: string;
      refunded: boolean;
      txHash: string;
    };
    refundAmount?: string;
  }> {
    const response = await this.client.post(`/xlayer/tokens/${launchId}/confirm-refund`, data);
    return response.data;
  }

  // BSC API Methods
  
  // Get BSC statistics
  async getBSCStats(): Promise<BSCStats> {
    const response = await this.client.get('/bsc/stats');
    // 后端返回的格式是 { success: true, data: { ... } }
    if (response.data.success && response.data.data) {
      return response.data.data;
    } else {
      return {
        totalTokens: 0,
        totalVolume: '0',
        activeTraders: 0,
        totalLaunches: 0,
        successfulLaunches: 0,
        averageRaise: '0'
      };
    }
  }

  // Get BSC tokens
  async getBSCTokens(params?: {
    page?: number;
    limit?: number;
    search?: string;
    filter?: 'all' | 'active' | 'launched' | 'cancelled';
    sort?: 'newest' | 'oldest' | 'price_high' | 'price_low' | 'market_cap' | 'volume';
  }): Promise<{ tokens: BSCToken[]; pagination: { page: number; limit: number; total: number; pages: number } }> {
    const response = await this.client.get('/bsc/tokens', { params });
    // 后端返回的格式是 { success: true, data: { tokens: [...], pagination: {...} } }
    if (response.data.success && response.data.data) {
      return response.data.data;
    } else {
      return { tokens: [], pagination: { page: 1, limit: 20, total: 0, pages: 0 } };
    }
  }

  // Get specific BSC token
  async getBSCToken(id: string): Promise<BSCToken | null> {
    try {
      const response = await this.client.get(`/bsc/tokens/${id}`);
      // 后端返回的格式是 { success: true, data: { ... } }
      if (response.data.success && response.data.data) {
        return response.data.data;
      } else {
        return null;
      }
    } catch (error) {
      console.error('Error fetching BSC token:', error);
      return null;
    }
  }

  // Get BSC token chart data
  async getBSCTokenChart(id: string, timeframe: '1h' | '24h' | '7d' | '30d' = '24h'): Promise<{
    prices: BSCPriceData[];
    timeframe: string;
  }> {
    const response = await this.client.get(`/bsc/tokens/${id}/chart`, {
      params: { timeframe }
    });
    return response.data;
  }

  // Create BSC token
  async createBSCToken(data: CreateBSCTokenParams & { imageUrl?: string }): Promise<BSCToken> {
    const response = await this.client.post('/bsc/tokens', data, {
      timeout: 90000 // 90 seconds for contract interaction
    });
    // 后端返回的格式是 { success: true, data: { ... } }
    if (response.data.success && response.data.data) {
      return response.data.data;
    } else {
      throw new Error(response.data.error || 'Failed to create BSC token');
    }
  }

  // Contribute to BSC token
  async contributeToBSCToken(tokenId: string, data: {
    contributor: string;
    amount: string;
    txHash?: string;
  }): Promise<{ success: boolean; tokensReceived?: string; newRaisedAmount?: string }> {
    const response = await this.client.post(`/bsc/tokens/${tokenId}/contribute`, data, {
      timeout: 60000 // 60 seconds for blockchain transaction
    });
    return response.data;
  }

  // Get user's BSC tokens
  async getUserBSCTokens(address: string): Promise<BSCToken[]> {
    const response = await this.client.get<BSCToken[]>(`/bsc/users/${address}/tokens`);
    return response.data;
  }

  // Get user's BSC contributions
  async getUserBSCContributions(address: string): Promise<BSCContribution[]> {
    const response = await this.client.get(`/bsc/users/${address}/contributions`);
    return response.data;
  }

  // Upload BSC token image
  async uploadBSCImage(file: File): Promise<{ url: string }> {
    const formData = new FormData();
    formData.append('image', file);
    
    const response = await this.client.post('/bsc/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      timeout: 30000 // 30 seconds for file upload
    });
    return response.data;
  }

  // Sync BSC token from contract
  async syncBSCToken(tokenId: string): Promise<BSCToken> {
    const response = await this.client.put<BSCToken>(`/bsc/tokens/${tokenId}/sync`);
    return response.data;
  }

  // Get BSC token holders (contributors)
  async getBSCTokenHolders(tokenId: string): Promise<string[]> {
    const response = await this.client.get(`/bsc/tokens/${tokenId}/contributors`);
    return response.data.data || []; // Response is wrapped in {success: true, data: [...]}
  }

  // Get BSC token transactions
  async getBSCTokenTransactions(tokenId: string, limit = 50): Promise<Transaction[]> {
    const response = await this.client.get(`/bsc/tokens/${tokenId}/transactions`, {
      params: { limit }
    });
    return response.data;
  }

  // Buy BSC tokens
  async buyBSCTokens(tokenId: string, data: {
    buyer: string;
    amount: string;
    slippage?: number;
    txHash?: string;
  }): Promise<{ success: boolean; tokensReceived?: string; pricePerToken?: string }> {
    const response = await this.client.post(`/bsc/tokens/${tokenId}/buy`, data, {
      timeout: 60000 // 60 seconds for blockchain transaction
    });
    return response.data;
  }

  // Sell BSC tokens
  async sellBSCTokens(tokenId: string, data: {
    seller: string;
    tokenAmount: string;
    slippage?: number;
    txHash?: string;
  }): Promise<{ success: boolean; ethReceived?: string; pricePerToken?: string }> {
    const response = await this.client.post(`/bsc/tokens/${tokenId}/sell`, data, {
      timeout: 60000 // 60 seconds for blockchain transaction
    });
    return response.data;
  }

  // Get BSC trade preview
  async getBSCTradePreview(tokenId: string, amount: string, type: 'buy' | 'sell'): Promise<{
    estimatedOutput: string;
    pricePerToken: string;
    priceImpact: number;
    fee: string;
  }> {
    const response = await this.client.get(`/bsc/tokens/${tokenId}/trade-preview`, {
      params: { amount, type }
    });
    return response.data;
  }
}

// Create a singleton instance
export const apiClient = new ApiClient();

// Export types and client
export default apiClient;
export type { ApiClient };
